package com.example.s.adapter;

import android.graphics.Color;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class InnerHolder extends RecyclerView.ViewHolder {

    private SparseArray<View> mViews;

    public InnerHolder(@NonNull View itemView) {
        super(itemView);
        mViews = new SparseArray<>();
    }

    public <T extends View> T getView(int id) {
        //先从缓存中找
        View view = mViews.get(id);
        if (view == null) {
            //找不到直接 findviewbyid
            view = itemView.findViewById(id);
            mViews.put(id, view);
        }

        return (T) view;
    }

    public InnerHolder setText(int id, CharSequence text) {
        TextView tv = getView(id);
        tv.setText(text);
        return this;
    }

    public InnerHolder setImageResource(int id, int resource) {
        View iv = getView(id);
        iv.setBackgroundResource(resource);
        return this;
    }

    public InnerHolder setSrcResource(int id, int resource) {
        ImageView iv = getView(id);
        iv.setImageResource(resource);
        return this;
    }

    public InnerHolder setOnClickListener(int id, View.OnClickListener listener) {
        View view = getView(id);
        view.setOnClickListener(listener);
        return this;
    }

    public InnerHolder setOnLongClickListener(int id, View.OnLongClickListener listener) {
        View view = getView(id);
        view.setOnLongClickListener(listener);
        return this;
    }

    public InnerHolder setTextColor(int id, String color) {
        TextView view = getView(id);
        view.setTextColor(Color.parseColor(color));
        return this;
    }

    public InnerHolder setVisibility(int id, boolean flag) {
        View view = getView(id);
        if (flag) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.INVISIBLE);
        }
        return this;
    }


}
